<script setup lang="ts">
import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage } from "element-plus";
import { stringToBase64 } from "@/utils/btoa";
import SvgIcon from "@/components/SvgIcon/index.vue";

// 全局组件 上传文件组件
const previewURL = ref("");
const imgVisible = ref(false);
const props = withDefaults(
  defineProps<{
    headers?: UploadProps["headers"];
    data?: UploadProps["data"];
    name?: UploadProps["name"];
    size?: number;
    max?: number;
    files?: UploadUserFile[];
    notip?: boolean;
    ext?: string[];
    disabled?: boolean;
    loadProgress?: number;
    progressFlag?: boolean;
  }>(),
  {
    name: "file",
    size: 500,
    max: 5,
    disabled: true,
    files: () => [],
    notip: false,
    ext: () => ["多种类型"],
    progressFlag: false,
  }
);
// 成功上传文件
const emits = defineEmits<{
  onSuccess: [res: any, file: UploadUserFile, fileList: UploadUserFile[]];
  onChange: [file: UploadUserFile, fileList: UploadUserFile[]];
  onRemove: [file: UploadUserFile, fileList: UploadUserFile[]];
}>();
// 上传文件之前的钩子
const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  const fileName = file.name.split(".");
  const fileExt = fileName.at(-1) ?? "";
  const isTypeOk = props.ext.includes(fileExt);
  const isSizeOk = file.size / 102400 / 102400 < props.size;
  if (!isTypeOk) {
    ElMessage.error(`上传文件只支持 ${props.ext.join(" / ")} 格式！`);
  }
  if (!isSizeOk) {
    ElMessage.error(`上传文件大小不能超过 ${props.size}MB！`);
  }
  return isTypeOk && isSizeOk;
};
// 当超出限制时，执行的钩子函数
const onExceed: UploadProps["onExceed"] = () => {
  ElMessage.warning("文件上传个数超过限制");
};
// 	文件上传成功时的钩子
const onSuccess: UploadProps["onSuccess"] = (res, file, fileList) => {
  emits("onSuccess", res, file, fileList);
};
// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const onChange: UploadProps["onChange"] = (file, fileList) => {
  emits("onChange", file, fileList);
};

function onRemove(file: any, fileList: any) {
  emits("onRemove", file, fileList);
}
// 预览
function preview(file: any) {
  const fileName = file.name.split(".");
  const fileExt = fileName.at(-1) ?? "";
  if (fileExt == "pdf") {
    // pdf预览
    previewURL.value = "http://oss.dachtech.info/" + file.path;
  } else {
    // 其他文件的预览
    const str = stringToBase64(file.url);
    previewURL.value = `http://1.116.4.57:8012/onlinePreview?url=${str}`;
  }
  imgVisible.value = true;
}

const customColorMethod = (percentage: number) => {
  if (percentage < 30) {
    return "#909399";
  }
  if (percentage < 70) {
    return "#e6a23c";
  }
  return "#67c23a";
};
</script>

<template>
  <div>
    <el-upload
      drag
      :auto-upload="false"
      :headers="headers"
      :data="data"
      :name="name"
      :before-upload="beforeUpload"
      :on-exceed="onExceed"
      :on-success="onSuccess"
      :on-change="onChange"
      :file-list="files as UploadUserFile[]"
      :limit="max"
    >
      <div v-if="disabled" class="slot">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          {{ $t("file.Dateienhierher")
          }}<em>{{ " " + $t("file.ZumHochladenklicken") }}</em>
        </div>
      </div>
      <template #tip>
        <div v-if="!notip && disabled">
          <div style="display: inline-block">
            <el-alert
              :title="
                $t('file.Unterstützung') +
                ` ${
                  ext.join(' / ') === '多种类型'
                    ? $t('file.MehrereTypen')
                    : ext.join(' / ')
                } ` +
                $t('file.Format') +
                ` ${size}MB，` +
                $t('file.überschreitet') +
                ` ${max} ` +
                $t('file.individuell')
              "
              type="info"
              show-icon
              :closable="false"
            />
          </div>
        </div>
      </template>
      <template #file="fileItem">
        <div
          style="
            height: 50px;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <span class="file" @click="preview(fileItem.file)">
            <svg-icon
              :icon-class="fileItem.file.name.split('.').at(-1)"
              style="font-size: 28px; margin-right: 5px; vertical-align: middle"
            />
            {{ fileItem.file.name }}
          </span>
          <span>
            <el-tooltip
              content="预览"
              placement="bottom"
              effect="light"
              v-if="fileItem.file.status == 'success'"
            >
              <svg-icon
                style="
                  font-size: 20px;
                  text-align: right;
                  vertical-align: middle;
                  margin-right: 10px;
                  color: var(--el-color-primary);
                  cursor: pointer;
                "
                :icon-class="'perview'"
                @click="preview(fileItem.file)"
              />
            </el-tooltip>
            <el-tooltip
              v-if="disabled && fileItem.file.status == 'success'"
              content="删除"
              placement="bottom"
              effect="light"
            >
              <svg-icon
                style="
                  font-size: 20px;
                  text-align: right;
                  vertical-align: middle;
                  margin-right: 5px;
                  color: var(--el-color-primary);
                  cursor: pointer;
                "
                :icon-class="'file_updelete'"
                @click="onRemove(fileItem.file, files)"
              />
            </el-tooltip>
          </span>
          <el-progress
            style="margin-top: 30px"
            v-if="fileItem.file.status == 'uploading'"
            :percentage="loadProgress"
            :color="customColorMethod"
            :text-inside="true"
            :stroke-width="15"
          ></el-progress>
        </div>
      </template>

      <el-dialog
        v-model="imgVisible"
        append-to-body
        title="预览"
        style="width: 60%"
        @close="false"
      >
        <iframe :src="previewURL" style="width: 100%; height: 600px"></iframe>
      </el-dialog>
    </el-upload>
  </div>
</template>

<style lang="scss" scoped>
.el-upload__tip {
  margin: 0;
  height: 0;
  padding: 0;
  width: 0;
}
:deep(.el-upload.is-drag) {
  display: inline-block;

  .el-upload-dragger {
    padding: 0;
  }

  &.is-dragover {
    border-width: 1px;
  }

  .slot {
    width: 300px;
    padding: 40px 0;
  }
}

.file:hover {
  color: var(--el-color-primary);
  cursor: pointer;
}
</style>
